const { car, cdr, cons } = require('./lang');
const { sqrt, atan2, cos, sin } = Math;

const square = (x) => x * x;

const real_part = (z) => car(z);
const imag_part = (z) => cdr(z);
const magnitude = (z) => sqrt(square(real_part(z)) + square(imag_part(z)));
const angle = (z) => atan2(imag_part(z), real_part(z));
const make_from_real_imag = (x, y) => cons(x, y);
const make_from_mag_ang = (r, a) => cons(r * cos(a), r * sin(a));

const add_complex = (z1, z2) => make_from_real_imag(
  real_part(z1) + real_part(z2),
  imag_part(z1) + imag_part(z2)
);

const sub_complex = (z1, z2) => make_from_real_imag(
  real_part(z1) - real_part(z2),
  imag_part(z1) - imag_part(z2)
);

const mul_complex = (z1, z2) => make_from_mag_ang(
  magnitude(z1) * magnitude(z2),
  angle(z1) + angle(z2)
);

const div_complex = (z1, z2) => make_from_mag_ang(
  magnitude(z1) / magnitude(z2),
  angle(z1) - angle(z2)
)